package com.situ.helloandroid;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.PersistableBundle;
import android.widget.TextView;

/**
 * Created by Gao on 2020/12/5.
 */
public class HandlerActivity extends Activity{
    private static  final  int MSG_UPDATE = 001;

    private TextView mTvNum;

    // 消息的处理者，这个的执行是在UI线程里面
    private Handler mHandler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what){
                case MSG_UPDATE:
                    int i = msg.arg1;
                    //更新控件的内容
                    mTvNum.setText(i + "");
                    break;
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_handler);
        mTvNum = (TextView) findViewById(R.id.tv_num);

        // 模拟下载线程，这是一个耗时的任务，所以要启动一个线程
        new Thread(new Runnable() {
            @Override
            public void run() {
                for (int i= 1; i <= 10; i++) {
                    // 在非UI线程里面更新了UI线程里面的控件
                   // mTvNum.setText(i + "");
                   // Only the original thread that created a view hierarchy can touch its views.

                    Message message = new Message();
                    message.what = MSG_UPDATE;// 这是标识是哪一个message
                    message.arg1 = i;// 传递数据
                    // 通过Handler发送，在UI线程里面更新控件
                    mHandler.sendMessage(message);

                    try {
                        Thread.sleep(1000);// 休眠1秒
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }).start();
    }

}
